<template>
  <div>
    <!--屠宰信息 -->
    <div style="margin-bottom: 40px;">
      <div>
        <span style="color: #3791EB;">屠宰信息</span>
        <el-button plain style="background-color: #F2F2F2;margin-left: 18px;width: 90px;margin-bottom: 15px;"
          @click="dialogBreedslaughter()">设置</el-button>
        <hr>
      </div>
      <div>
        <table>
          <tr>
            <td style="width: 300px;">屠宰批次 : {{ AddSlaughterObj.slaughterBatch }}</td>
            <td>到厂均重 : {{ AddSlaughterObj.kg ? AddSlaughterObj.kg + "公斤" : AddSlaughterObj.kg }}</td>
          </tr>
          <tr>
            <td>到厂时间 : {{ AddSlaughterObj.arriveTime ? moment(AddSlaughterObj.arriveTime).format("yyyy年MM月DD HH:mm:ss")
              : ""
            }}</td>
            <td>屠宰时间 : {{ AddSlaughterObj.slaughterTime ?
              moment(AddSlaughterObj.slaughterTime).format("yyyy年MM月DD HH:mm:ss")
              : ""
            }}</td>
          </tr>
        </table>
      </div>
      <!-- 屠宰信息设置弹框 -->
      <div>
        <el-dialog v-model="dialogFormSlaughter" title="屠宰信息" width="500" draggable="true">
          <el-form ref="ruleFormRef" style="max-width: 600px" :model="AddSlaughterObj" :rules="ruless"
            label-width="auto" class="demo-ruleForm" :size="formSizeSlaughter" status-icon>
            <el-form-item label="屠宰批次" prop="slaughterBatch">
              <el-input v-model="AddSlaughterObj.slaughterBatch" show-word-limit maxlength="30" />
            </el-form-item>
            <el-form-item label="到厂均重（公斤）" prop="kg">
              <el-input v-model="AddSlaughterObj.kg" show-word-limit maxlength="5" />
            </el-form-item>
            <el-form-item label="到厂时间" prop="arriveTime">
              <el-date-picker v-model="AddSlaughterObj.arriveTime" type="datetime" placeholder="到厂时间" />
            </el-form-item>
            <el-form-item label="屠宰时间" prop="slaughterTime">
              <el-date-picker v-model="AddSlaughterObj.slaughterTime" type="datetime" placeholder="屠宰时间" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitFormslaughter(ruleFormRef)">
                保存
              </el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
    </div>
    <!-- 相关资质 -->
    <div style="margin-bottom: 40px;">
      <div>
        <span style="color: #3791EB;">相关资质</span>
        <hr>
        <el-upload v-model:file-list="fileList" action="https://localhost:7281/api/UploadTuPian"
          list-type="picture-card" :on-preview="handlePictureCardPreview" @change="addTestModel.pTyper = 4"
          :on-remove="handleRemove" :on-success="handleAvatarSuccess" class="aaimg">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible" class="imgyl">
          <img w-full :src="dialogImageUrl" alt="Preview Image" class="imgyll" />
        </el-dialog>
      </div>
    </div>
    <!--企业信息 -->
    <div style="margin-bottom: 40px;">
      <div>
        <span style="color: #3791EB;">企业信息</span>
        <el-button plain style="background-color: #F2F2F2;margin-left: 18px;width: 90px;margin-bottom: 15px;"
          @click="dialogBreedEnter()">设置</el-button>
        <hr>
      </div>
      <div>
        <table>
          <tr>
            <td style="width: 300px;">公司名称 : {{ AddEnterObj.slaughterName }}</td>
            <td>
              成立时间 :
              {{ AddEnterObj.slaughterCreteTime ? moment(AddEnterObj.slaughterCreteTime).format("yyyy年MM月DD") :
                ""
              }}
            </td>
          </tr>
          <tr>
            <td>公司地址 : {{ AddEnterObj.slaughterAdder }}</td>
          </tr>
          <tr>
            <td>公司简介 : {{ AddEnterObj.slaughterBrief }}</td>
          </tr>
        </table>
      </div>
      <!-- 企业信息设置弹框 -->
      <div>
        <el-dialog v-model="dialogFormEnter" title="企业信息" width="500" draggable="true">
          <el-form ref="ruleFormRef" style="max-width: 600px" :model="AddEnterObj" :rules="rulesEnter"
            label-width="auto" class="demo-ruleForm" :size="formSizeEnter" status-icon>
            <el-form-item label="公司名称" prop="slaughterName">
              <el-input v-model="AddEnterObj.slaughterName" show-word-limit maxlength="30" />
            </el-form-item>
            <el-form-item label="公司地址" prop="slaughterAdder">
              <el-cascader size="large" :options="options" v-model="provinces" @change="handleChange"
                placeholder="请选择省市区" show-word-limit maxlength="100">
              </el-cascader>
            </el-form-item>
            <el-form-item label="成立时间" prop="slaughterCreteTime">
              <el-date-picker v-model="AddEnterObj.slaughterCreteTime" type="date" placeholder="成立时间"
                style="width: 100%" />
            </el-form-item>
            <el-form-item label="公司简介" prop="slaughterBrief">
              <el-input v-model="AddEnterObj.slaughterBrief" show-word-limit maxlength="500" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitFormEnter(ruleFormRef)">
                保存
              </el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
    </div>
    <!--企业照片 -->
    <div style="margin-bottom: 40px;">
      <div>
        <span style="color: #3791EB;">企业照片</span>
        <hr>
        <el-upload v-model:file-list="fileListEnter" action="https://localhost:7281/api/UploadTuPian"
          list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemoveEnter"
          :on-success="handleAvatarSuccess" @change="addTestModel.pTyper = 5" class="aaimg">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible" class="imgyl">
          <img w-full :src="dialogImageUrl" alt="Preview Image" class="imgyll" />
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { compile, computed, onMounted, reactive, ref, watch } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from '@/stores/counter';
import DepData from '@/stores/departmentData'
import { Delete, Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { pcaTextArr } from "element-china-area-data";//引入中国地址



//实现地址
const options = pcaTextArr;
//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();
//跳转传参
const route = useRoute();


//#region  企业信息

//添加企业表单
const AddEnterObj = reactive({
  "enterId": null,              //主键
  //////////////////////养殖企业信息////////////////////////////
  "breedName": null,            //养殖场
  "breedChargeName": null,      //负责人
  "breedNum": null,             //存栏数量
  //////////////////////屠宰企业信息////////////////////////////
  "slaughterName": "",        //公司名称
  "slaughterAdder": "",       //公司地址
  "slaughterProvinceId": "",  //省份
  "slaughterCityId": "",      //市
  "slaughterCountyId": "",    //县
  "slaughterCreteTime": "",   //成立时间
  "slaughterBrief": "",       //公司简介
  //////////////////////深加工企业信息////////////////////////////
  "deepName": null,             //深加工公司名称
  "deepNumber": null,           //生产许可证号
  //////////////////////公共字段////////////////////////////
  "traceaBatch": store.ccTrace.traceaBatch,          //生产批次
  "traceaIsDelete": false     // 逻辑删除 false 未删除  true 删除
})

const dialogFormEnter = ref(false) //对话框开关

const ruleFormRefEnter = ref<FormInstance>()
const formSizeEnter = ref<ComponentSize>('default')
//企业效验
const rulesEnter = reactive<FormRules>({
  // 公司名称
  //   1、必填项
  //   2、允许输入任意字符（主要为中文、字母）
  //   3、不允许输入非特殊字符（如逗号、问号等）
  //   4、最多支持输入 30 位字符
  slaughterName: [
    { required: true, message: '必填项', trigger: 'blur' },
    { min: 0, max: 30, message: '最多支持输入 30 位字符', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/, message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur'
    },
  ],
  //地址
  slaughterAdder: [
    { required: true, message: '必填项', trigger: 'blur' },
    { min: 0, max: 100, message: '最多支持输入 100 位字符', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/, message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur'
    },
  ],
  //成立时间
  slaughterCreteTime: [
    { required: true, message: '必填项', trigger: 'blur' },
  ],
  //公司简介
  slaughterBrief: [
    // { required: true, message: '必填项', trigger: 'blur' },
    { min: 0, max: 500, message: '最多支持输入 500 位字符', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/, message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur'
    },
  ],
})

//打开企业对话框
const dialogBreedEnter = () => {
  //清空操作
  dialogFormEnter.value = true
  FanTianAdder(AddEnterObj.slaughterProvinceId, AddEnterObj.slaughterCityId, AddEnterObj.slaughterCountyId)

}

//省市县储存
let provinces: any = ref([]);

//传值地址
const FanTianAdder = (id1: string, id2: string, id3: string) => {
  provinces = [id1.toString(), id2.toString(), id3.toString()]
}

//获取地址省市县及公司详细地址
const handleChange = (values: any) => {
  provinces.value = values;
  console.log(options)
  //公司详细地址
  AddEnterObj.slaughterAdder = values.join('')
  console.log(AddEnterObj.slaughterAdder, "公司详细地址")
  AddEnterObj.slaughterProvinceId = values[0] //省
  AddEnterObj.slaughterCityId = values[1]     //市
  AddEnterObj.slaughterCountyId = values[2]   //县
}

//添加企业信息
const submitFormEnter = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post('https://localhost:7281/api/Trace/AddUpdateEnterprise', AddEnterObj).then(res => {
        if (res.data.code === 220) {
          //设置成功
          ElMessage.success("设置成功")
        } else if (res.data.code === 221) {
          //设置失败
          ElMessage.error("设置失败")
        } else {
          //添加失败
          ElMessage.error("设置出错")
        }
        dialogFormEnter.value = false //关闭对话框
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//显示反填企业信息
const showEnter = () => {
  axios.get(`https://localhost:7070/api/Trace/GetEnterprise?TraceaBatch=${store.ccTrace.traceaBatch}`).then(res => {
    console.log(res.data.data, "反填的饲养信息")
    AddEnterObj.slaughterName = res.data.data[0].slaughterName
    AddEnterObj.slaughterAdder = res.data.data[0].slaughterAdder
    AddEnterObj.slaughterProvinceId = res.data.data[0].slaughterProvinceId
    AddEnterObj.slaughterCityId = res.data.data[0].slaughterCityId
    AddEnterObj.slaughterCountyId = res.data.data[0].slaughterCountyId
    AddEnterObj.slaughterCreteTime = res.data.data[0].slaughterCreteTime
    AddEnterObj.slaughterBrief = res.data.data[0].slaughterBrief

  })
}


//#endregion


//#region 屠宰信息
//添加屠宰表单
const AddSlaughterObj = reactive({
  "slaughterId": null,
  "slaughterBatch": "",  //屠宰批次
  "kg": "",                                              //到厂均重（公斤）
  "arriveTime": "",                                     //到厂时间
  "slaughterTime": "",                                  //屠宰时间
  "traceaBatch": store.ccTrace.traceaBatch,             //溯源生产批次
  "traceaIsDelete": false                               //逻辑删除 false 未删除  true 删除
})


const dialogFormSlaughter = ref(false) //对话框开关

const ruleFormRef = ref<FormInstance>()
const formSizeSlaughter = ref<ComponentSize>('default')
//屠宰效验
const ruless = reactive<FormRules>({
  // 屠宰批次
  //   1、必填项
  //   2、允许输入任意字符（主要为中文、字母）
  //   3、不允许输入非特殊字符（如逗号、问号等）
  //   4、最多支持输入 30 位字符
  slaughterBatch: [
    { required: true, message: '必填项', trigger: 'blur' },
    { min: 0, max: 30, message: '最多支持输入 30 位字符', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/, message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur'
    },
  ],
  //到厂均重（公斤）
  kg: [
    { required: true, message: '必填项', trigger: 'blur' },
    // { min: 0, max: 5, message: '最多支持输入 5 位字符', trigger: 'blur' },
    {
      pattern: /^\d+$/, message: '请输入数字', trigger: 'blur'
    }
  ],
  //到厂时间
  arriveTime: [
    { required: true, message: '必填项', trigger: 'blur' },
  ],
  //屠宰时间
  slaughterTime: [
    { required: true, message: '必填项', trigger: 'blur' },
  ],

})

//打开屠宰对话框
const dialogBreedslaughter = () => {
  //清空操作

  AddSlaughterObj.slaughterBatch = `SZ${Math.floor(Date.now() / 1)}` //自动添加批次号
  dialogFormSlaughter.value = true //打开对话框
}

//添加屠宰信息
const submitFormslaughter = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post('https://localhost:7281/api/Trace/AddUpdateSlaughter', AddSlaughterObj).then(res => {
        if (res.data.code === 220) {
          //设置成功
          ElMessage.success("设置成功")
        } else if (res.data.code === 221) {
          //设置失败
          ElMessage.success("设置失败")
        } else {
          //添加失败
          ElMessage.error("设置出错")
        }
        dialogFormSlaughter.value = false //关闭对话框
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//显示反填屠宰信息
const showSlaughter = () => {
  axios.get(`https://localhost:7070/api/Trace/GetSlaughter?TraceaBatch=${store.ccTrace.traceaBatch}`).then(res => {
    console.log(res.data.data, "反填的饲养信息")
    AddSlaughterObj.slaughterBatch = res.data.data[0].slaughterBatch
    AddSlaughterObj.kg = res.data.data[0].kg
    AddSlaughterObj.arriveTime = res.data.data[0].arriveTime
    AddSlaughterObj.slaughterTime = res.data.data[0].slaughterTime
  })
}


//#endregion


//#region 相关资质信息
//预览开关
const dialogVisible = ref(false)
//预览图片路径
const dialogImageUrl = ref('')

//添加请求表单
const addTestModel = reactive({
  "url": "",
  "pTyper": 0,
  "traceaBatch": store.ccTrace.traceaBatch,
  "traceaIsDelete": false
})

//添加相关资质图片请求
const addTest = () => {
  axios.post('https://localhost:7281/api/Trace/AddTest', addTestModel).then(res => {
    if (res.data.code == 212) {
      // 添加成功
      ElMessage.success(res.data.msg)
    }
  })
}

//储存相关资质图片列表
const fileList = ref<UploadUserFile[]>([])

//显示相关资质图片
const imgshow = () => {
  axios.get(`https://localhost:7070/api/Trace/GetTest?PTyper=4&TraceaBatch=${store.ccTrace.traceaBatch}&TraceaIsDelete=false`).then(res => {
    fileList.value = res.data.data
  })
}


//删除相关资质图片
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, "获取删除数据uploadFile")
  // console.log(uploadFiles, "获取删除数据uploadFiles")
  axios.get(`https://localhost:7281/api/Trace/DeleteTest?Url=${uploadFile.url}&PTyper=4&TraceaBatch=${store.ccTrace.traceaBatch}`).then(res => {
    if (res.data.code == 204) {
      ElMessage.success("图片删除成功")
    } else if (res.data.code = 205) {
      ElMessage.error("图片删除失败")
    } else {
      ElMessage.error("图片删除出现错误")
    }
  })
}

//预览图片
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}


//图片添加操作
//定义图片存放变量
const imageUrl = ref('')

//上传后获取数据url
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  addTestModel.url = response.imgss;
  console.log(response, '返回的图片数据')
  console.log(addTestModel.url, "上传图片获取路径")
  addTest()
}

//图片上传前操作
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error('Avatar picture size can not exceed 2MB!')
  //   return false
  // }
  return true
}

//#endregion


//#region 企业图片
//储存企业图片列表
const fileListEnter = ref<UploadUserFile[]>([])


//企业图片显示
const imgshowEnter = () => {
  axios.get(`https://localhost:7070/api/Trace/GetTest?PTyper=5&TraceaBatch=${store.ccTrace.traceaBatch}&TraceaIsDelete=false`).then(res => {
    fileListEnter.value = res.data.data
  })
}

//删除企业图片
const handleRemoveEnter: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, "获取删除数据uploadFile")
  // console.log(uploadFiles, "获取删除数据uploadFiles")
  axios.get(`https://localhost:7281/api/Trace/DeleteTest?Url=${uploadFile.url}&PTyper=5&TraceaBatch=${store.ccTrace.traceaBatch}`).then(res => {
    if (res.data.code == 204) {
      ElMessage.success("图片删除成功")
    } else if (res.data.code = 205) {
      ElMessage.error("图片删除失败")
    } else {
      ElMessage.error("图片删除出现错误")
    }
  })
}

//#endregion




onMounted(() => {
  //反填屠宰信息数据
  showSlaughter()
  //显示相关资质图片
  imgshow()
  //企业图片显示
  imgshowEnter();
  //显示反填企业信息
  showEnter();
})



</script>

<style scoped></style>